package com.qf.service.Impl;
/* stohox
013 7/13 上午 10:02 */
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.entity.Category;
import com.qf.entity.Course;
import com.qf.mapper.CategoryMapper;
import com.qf.service.CategoryService;
import com.qf.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public ResultVO listCategories() {
        List<Category> categoryList = categoryMapper.selectAllCategories();
        ResultVO resultVO = new ResultVO(666, "success", categoryList);
        return resultVO;
    }

    @Override
    public ResultVO selectFirstLevelCategories(String id) {
        List<Category> categoryList = categoryMapper.selectFirstLevelCategories(id);
        ResultVO resultVO = new ResultVO(666, "success", categoryList);
        return resultVO;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public ResultVO selectCourse(String id) {
        //根据商品id查询redis
        String courseInfo = (String) stringRedisTemplate.boundHashOps("courses").get(id);
        //如果redis中有相关数据,则从redis中查询
        try {
        if(courseInfo != null){
                Course[] course = objectMapper.readValue(courseInfo, Course[].class);
                //封装课程信息
                HashMap<String,Object> basicInfo = new HashMap<>();
                basicInfo.put("course",course);
                return new ResultVO(666,"从redis中查询成功",basicInfo);


        }else {
            //如果redis中没有相关数据，则从数据库中查询
            List<Category> categoryList = categoryMapper.selectFirstLevelCategories(id);
            //查到之后将数据写入到redis之中
            stringRedisTemplate.boundHashOps("courses").put(id,objectMapper.writeValueAsString(categoryList));
            HashMap<String, Object> basicInfo = new HashMap<>();
            basicInfo.put("course",categoryList);
            return new ResultVO(666,"从数据库中查询成功",basicInfo);
        }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultVO(0,"fail",null);
    }

}
